/*================================================================
*   Copyright (C) 2020 belonging to YangZhengQing. All rights reserved.
*   
*   文件名称：named_socket_client.c
*   创 建 者：YangZhengQing
*   创建日期：2020年03月11日
*   描    述：
*
*================================================================*/


//#include "named_socket_client.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCKET_PATH "socket_path"//命名socket通信路径
#define MSG_STR "Hello,I am client, nice to meet you!"
#define SIZE 50
int main(int argc, char **argv)
{

	int						sockfd = -1;
	struct sockaddr_un	server_addr;
	char					buff[SIZE];
	int						rv = -1;

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);//创建套接字，第三参数0会自动匹配与参数二适应的协议
	if(sockfd < 0)
	{
		printf("socket error:%s\n",strerror(errno));
		return 0;
	}

	//初始化服务器
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sun_family = AF_UNIX;
	strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(SOCKET_PATH)-1);//减一是因为去掉字符串中‘\0’
	
	if( connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)//连接服务器
	{
		printf("connect error:%s\n",strerror(errno));
		goto Cleanup;
	}

	if( (rv = write(sockfd, MSG_STR, strlen(MSG_STR))) < 0 )//向服务器写数据
	{
		printf("write error:%s\n",strerror(errno));
		goto Cleanup;
	}
	printf("Send [%d] bytes to named_server successfully!\n",rv);

	memset(buff, 0, sizeof(buff));
	if((rv = read(sockfd, buff, sizeof(buff))) < 0)
	{
		printf("read error:%s\n",strerror(errno));
		goto Cleanup;
	}
	else if(rv == 0)
	{
		printf("named_server disconnct!\n");
	}
	printf("%s\n",buff);

Cleanup:
	close(sockfd);
	return 0;
}
